package com.cn.server.sever;

import com.cn.common.core.codc.RequestDecoder;
import com.cn.common.core.codc.ResponseEncoder;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;

/**
 * @Author: jia
 * @Descirption:
 * @Date: 2018/5/21 15:46
 * @Modified By:
 */


public class ChannelInitializerImpl extends ChannelInitializer {
    private EventLoopGroup serviceGroup;

    public ChannelInitializerImpl(){}
    public ChannelInitializerImpl(EventLoopGroup serviceGroup) {
        this.serviceGroup = serviceGroup;
    }

    @Override
    protected void initChannel(Channel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        pipeline.addFirst(new HandlerManager());
        IdleStateHandler idleStateHandler = new IdleStateHandler(5, 5, 10);
        pipeline.addLast(idleStateHandler);
        pipeline.addLast(serviceGroup,new ServerHandler());
/*
        //======================== 自定义的协议 =====================////
        //encoer按照ChannelOutboundHandler，逆序执行
        //decoder按照ChannelIntboundHandler，按照顺序执行
        IdleStateHandler idleStateHandler = new IdleStateHandler(5, 5, 10);

        pipeline.addLast(idleStateHandler);
        pipeline.addLast(new RequestDecoder());
        pipeline.addLast(new ResponseEncoder());
        //======================= websocket =======================///
        pipeline.addLast(new HttpServerCodec());
        //以块的方式来写的处理器
        pipeline.addLast(new ChunkedWriteHandler());
        //netty是基于分段请求的，HttpObjectAggreator的作用是将
        //请求分段再聚合，参数是聚合字节的最大长度为512kb
        pipeline.addLast(new HttpObjectAggregator(512*1024));
        //创建一个http请求Handler
        pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
        //帧的传输类型，这里使用的是处理文本类型的Handler
        System.out.println("pipeline:" + Thread.currentThread().getName());
        pipeline.addLast(serviceGroup, new ServerHandler());
*/

    }
}
